<template>
  <div>
    <q-card>
      <div style="display: flex; flex-direction: column; align-items: center">
        <!-- Excel展示容器 -->
        <div id="luckysheet" style="width: 75vw; height: 75vh"></div>

        <!-- 保存并上传按钮 -->
        <q-btn label="保存并上传" flat color="primary" @click="saveAndUpload" />
      </div>
    </q-card>
  </div>
</template>

<script setup>
import { ref, watch, nextTick } from "vue";
import LuckyExcel from "luckyexcel";
import * as XLSX from "xlsx"; // 引入 xlsx 库
import { createFile, updateFile } from "src/api/api";
import { useQuasar } from "quasar";
import { defineEmits } from 'vue';

// 定义一个事件用于发送消息给父组件
const emit = defineEmits(['fileUploadFun']);
const $q = useQuasar();
// 接收父组件传递的文件 (props)
const props = defineProps({
  excelFile: {
    type: ArrayBuffer,
    required: true,
  },
  selectedProject: {
    type: [String, Number], // 根据实际的项目 ID 类型选择 String 或 Number
    required: true,
  },
});
// 处理传递过来的Excel文件
const processExcelFile = (arrayBuffer) => {
  LuckyExcel.transformExcelToLucky(
    arrayBuffer,
    (exportJson, luckysheetfile) => {
      // 检查文件内容是否成功转换
      if (!exportJson.sheets || exportJson.sheets.length === 0) {
        console.error("无法读取excel文件的内容");
        this.$q.notify({
          type: "warning",
          message: "无法读取excel文件的内容，目前仅支持xlsx类型!",
        });
        return;
      }

      // 销毁之前的 luckysheet 实例以防冲突
      if (window.luckysheet) {
        window.luckysheet.destroy();
      }

      // 等待 DOM 更新后创建 Luckysheet 实例
      nextTick(() => {
        window.luckysheet.create({
          container: "luckysheet", // luckysheet 是容器的 id
          lang: "zh", // 设定表格语言
          row: 100, // 默认100行
          showinfobar: false,
          data: exportJson.sheets, // 传递转换后的数据
        });
      });
    }
  );
};

// 保存并上传修改后的内容
const saveAndUpload = async () => {
  // 1. 获取 Luckysheet 修改后的数据
  const luckysheetData = window.luckysheet.getAllSheets(); // 获取所有表格的数据

  // 2. 创建一个新的工作簿
  const workbook = XLSX.utils.book_new();

  // 3. 遍历 Luckysheet 的每个表，并添加到工作簿中
  luckysheetData.forEach((sheet) => {
    const sheetData = sheet.data.map(
      (row) => row.map((cell) => (cell && cell.v ? cell.v : "")) // 获取单元格的值
    );

    // 转换数据为 Excel Sheet 格式
    const worksheet = XLSX.utils.aoa_to_sheet(sheetData);
    XLSX.utils.book_append_sheet(workbook, worksheet, sheet.name); // 添加到工作簿
  });

  // 4. 将工作簿转换为 ArrayBuffer
  const excelArrayBuffer = XLSX.write(workbook, {
    bookType: "xlsx",
    type: "array",
  });

  // 5. 将 ArrayBuffer 转换为 Blob
  const excelBlob = new Blob([excelArrayBuffer], {
    type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
  });
  const excelFile = new File([excelBlob], props.excelFile.name, {
    type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", // 或者使用 "application/vnd.ms-excel"
  });

  // 7. 上传文件
  await updateFile({
    project_id: props.selectedProject,
    uploaded_file: excelFile,
  })
    .then((response) => {
      if (response.data.code == 200) {
        emit("fileUploadFun", props.excelFile);
        $q.notify({ type: "positive", message: "文件上传成功" });
      } else {
        $q.notify({ type: "negative", message: "文件上传失败" });
      }
    })
    .catch((error) => {
      console.error("文件上传失败:", error);
      $q.notify({
        type: "negative",
        message: "文件上传失败",
      });
    });
};

// 监听 excelFile 变化
watch(
  () => props.excelFile,
  (newFile) => {
    if (newFile) {
      processExcelFile(newFile);
    }
  },
  { immediate: true }
);
</script>

<style scoped></style>
